import base64
import time
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.cache import cache_page  # 倒入缓存
from django.core import mail

def set_cookie_view(request):
    if request.method == "GET":
        return render(request, "login.html")
    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        if username != "zhaoliying" or password != "123456":
            return HttpResponse("user or password error")

        # 设置cookie
        resp = HttpResponse("congratulation")
        b64_username = base64.b64encode(username.encode()).decode()
        resp.set_cookie("username", b64_username, 300)
        return resp


def get_cookie_view(request):
    """
    获取cookie,得到用户标识
    """
    b64_username = request.COOKIES.get("username")
    if not b64_username:
        return HttpResponse("已经过期")
    username = base64.b64decode(b64_username.encode()).decode()

    return HttpResponse(f"欢迎您,{username}")


def set_session_view(request):
    """
    1/登陆
    2/存储用户标识
    """
    request.session["username"] = "zhaoliying"
    return HttpResponse("Congratulation")


def get_session_view(request):
    """
    1/获取session
    2/查询数据
    """
    username = request.session.get("username")
    return HttpResponse(f"欢迎您, {username}")


# @cache_page(30)
def test_cache_view(request):
    print("\033[31m我和你，男和女，都逃不过爱情!\033[0m")
    return HttpResponse(f"时间辍, {time.time()}")


def test_view(request):
    return HttpResponse("欢迎")


def send_email_view(request):
    mail.send_mail(
        subject='爱你哟',
        message='爱意东升西落，浪漫至死不渝',
        from_email='2523810765@qq.com',
        recipient_list=['2523810765@qq.com'],
    )
    return HttpResponse("发送成功")
